package Interview.Calculator;

import java.util.Stack;

public class Calc {
    public static void main(String[] args) {
        int i = Solution.calculate("1-1+1");
        System.out.println(i);
    }
}

// 面试题 16.26. 计算器
class Solution {
    public static int calculate(String s) {
        Stack<Integer> ns = new Stack<>();
        Stack<Character> os = new Stack<>();
        String n = "";
        char op1;
        for(char c : s.toCharArray()){
            if(c==' ') continue;
            if(c>='0'&&c<='9'){ //数字
                n+=c;
            }else{//符号
                //先把树加进数栈
                ns.add(Integer.parseInt(n));
                n="";
                while(!os.isEmpty()&&canCalc((op1=os.peek()),c)){
                    os.pop();
                    int n2 = ns.pop();
                    int n1 = ns.pop();
                    ns.add(calc(op1, n1, n2));
                }
                os.add(c);
            }
        }
        if(!n.equals(""))  ns.add(Integer.parseInt(n));
        while(!os.isEmpty()){
            char op = os.pop();
            int n2 = ns.pop();
            int n1 = ns.pop();
            ns.add(calc(op, n1, n2));
        }
        return ns.pop();
    }

    private static boolean canCalc(char op1,char op2){
        return !((op1=='+'||op1=='-')&&(op2=='*'||op2=='/'));
    }

    private static int calc(char op,int n1,int n2){
        switch(op){
            case'+':
                return n1+n2;
            case'-':
                return n1-n2;
            case'*':
                return n1*n2;
            case'/':
                return n1/n2;
        }
        return -1;
    }
}


